package com.fjwt.gz.service.activity.coupon.notify;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.constants.ApiCodeEnum;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.coupon.gtpay.GtpayCouponNotifyService;
import com.fjwt.gz.db.entity.AwardCouponNotifyEntity;
import com.fjwt.gz.db.entity.FansAwardEntity;
import com.fjwt.gz.db.entity.PayOrderEntity;
import com.fjwt.gz.interfaces.ChannelCouponWriteService;
import com.fjwt.gz.service.impl.AwardCouponNotifyService;
import com.fjwt.gz.service.impl.FansAwardService;
import com.fjwt.gz.service.impl.PayOrderService;
import com.fjwt.gz.service.impl.ScoreRecordTotalService;
import com.fjwt.gz.service.activity.BaseActivityService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

@Service
@Slf4j
public class GtpayCouponWriteService implements ChannelCouponWriteService {

    private static final Logger gtPayLogger = LoggerFactory.getLogger("gtPay");

    @Autowired
    private AwardCouponNotifyService awardCouponNotifyService;
    @Autowired
    private FansAwardService fansAwardService;
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private ScoreRecordTotalService scoreRecordService;
    @Autowired
    private GtpayCouponNotifyService gtpayCouponNotifyService;
    private static String logPrefix = "国通卡券核销回调:";


    @Override
    public String addNotifyRecord(Map<String, Object> requestMap) {

        gtPayLogger.info(logPrefix + "添加回调信息记录进来的参数是：{}", JSONUtil.toJsonStr(requestMap));
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.TEXT_HTML);
        Date date = new Date();
        AwardCouponNotifyEntity couponNotifyEntity = new AwardCouponNotifyEntity();
        String couponId = MapUtil.getStr(requestMap, "coupon_id");
        gtPayLogger.info(logPrefix + "三方卡券ID:{}", couponId);

        LambdaQueryWrapper<FansAwardEntity> fansAwardGw = FansAwardEntity.gw();
        fansAwardGw.eq(FansAwardEntity::getCouponThirdId, couponId);
        FansAwardEntity fansAwardEntity = fansAwardService.getBaseMapper().selectOne(fansAwardGw);
        if (ObjectUtil.isEmpty(fansAwardEntity)) {
            gtPayLogger.info("卡券ID：{}，此卡券不是营销平台创建，直接返回，不记录数据库", couponId);
            return JSONUtil.toJsonStr(ApiRes.fail(ApiCodeEnum.SYS_WXCOUPON_FAIL_NOTIFY));
        }

        if ("USED".equals(MapUtil.getStr(requestMap, "status"))) {
            couponNotifyEntity.setNotifyState(0);//已核销
        } else if ("SENDED".equals(MapUtil.getStr(requestMap, "status"))) {
            couponNotifyEntity.setNotifyState(1);//未核销
        } else if ("EXPIRED".equals(MapUtil.getStr(requestMap, "status"))) {
            couponNotifyEntity.setNotifyState(2);//已过期
        }
        couponNotifyEntity.setCouponThirdId(couponId);
        couponNotifyEntity.setIfcode("gtpay");
        couponNotifyEntity.setState(1);//回调进来的都是状态1未同步
        couponNotifyEntity.setNotifyJson(JSONUtil.toJsonStr(requestMap));
        couponNotifyEntity.setCreatedAt(date);
        couponNotifyEntity.setUpdatedAt(date);
        couponNotifyEntity.setSourceType(1);
        gtPayLogger.info(logPrefix + "添加回调信息记录:{}", JSONUtil.toJsonStr(couponNotifyEntity));
        boolean save = awardCouponNotifyService.save(couponNotifyEntity);
        if (save == true) {
            return JSONUtil.toJsonStr(ApiRes.fail(ApiCodeEnum.SYS_WXCOUPON_SUCCESS_NOTIFY));
        } else {
            return JSONUtil.toJsonStr(ApiRes.fail(ApiCodeEnum.SYS_TLPAY_FAIL_COUPON_NOTIFY));
        }
    }

    @Override
    public Map<String, Object> paraseParamters(HttpServletRequest request) throws IOException {
        return gtpayCouponNotifyService.paraseParamters(request, null);
    }

    @Override
    public void couponDoNotice(AwardCouponNotifyEntity couponNotifyEntity) throws Exception {
        gtPayLogger.info(logPrefix + "处理逻辑进来的参数是：{}", JSONUtil.toJsonStr(couponNotifyEntity));
        //通过卡券三方id是否存在，如不存在，更新回调记录表，添加备注
        LambdaQueryWrapper<FansAwardEntity> fansAwardGw = FansAwardEntity.gw();
        fansAwardGw.eq(FansAwardEntity::getCouponThirdId, couponNotifyEntity.getCouponThirdId());
        FansAwardEntity fansAwardEntity = fansAwardService.getBaseMapper().selectOne(fansAwardGw);

        if (ObjectUtil.isNotEmpty(fansAwardEntity)) {
            if (fansAwardEntity.getState() == 1) {
                //卡券不是英雄啊平台创建
                AwardCouponNotifyEntity couponNotifyUpdate = new AwardCouponNotifyEntity();
                couponNotifyUpdate.setCouponNotifyId(couponNotifyEntity.getCouponNotifyId());
                couponNotifyUpdate.setState(2);
                couponNotifyUpdate.setRemark("此订单已经推送过");
                gtPayLogger.info(logPrefix + "处理逻辑,此卡券此订单已经推送过,更新的数据是：{}", JSONUtil.toJsonStr(couponNotifyUpdate));
                awardCouponNotifyService.updateById(couponNotifyUpdate);
            } else {
                // 处理卡券核销是否进行奖励积分
                scoreRecordService.couponWriteSendScore(fansAwardEntity);
                //是卡券营销平台创建,卡券核销后的处理
                gtPayLogger.info(logPrefix + "extraJson:{}", fansAwardEntity.getExtraJson());
                JSONObject extraJson = JSONObject.parseObject(fansAwardEntity.getExtraJson());
                if (extraJson != null && fansAwardEntity.getExtraJson().contains("templateNo")) {
                    String templateNo = extraJson.getString("templateNo");
                    BaseActivityService activityService = SpringBeansUtil.getBean(templateNo + "Service", BaseActivityService.class);
                    // 支付通道接口实现不存在
                    if (activityService == null) {
                        gtPayLogger.info(templateNo + "Service,接口不存在");
                        throw new BizException(templateNo + "Service,接口不存在");
                    }
                    JSONObject json = JSONObject.parseObject(JSONUtil.toJsonStr(fansAwardEntity));
                    activityService.run(json);
                }
                FansAwardEntity fansAwardEntityUpdate = new FansAwardEntity();
                fansAwardEntityUpdate.setFansAwardId(fansAwardEntity.getFansAwardId());
                fansAwardEntityUpdate.setState(1);
                fansAwardEntityUpdate.setWriteTime(new Date());
                //如果能通过三方卡券id查询到订单，则添加商户号，（此订单核销属于新平台的订单，如果没有则表示是老平台的订单，就没有商户号）
                LambdaQueryWrapper<PayOrderEntity> payOrderGw = PayOrderEntity.gw();
                payOrderGw.eq(PayOrderEntity::getCouponThirdId, fansAwardEntity.getCouponThirdId());
                PayOrderEntity payOrderEntity = payOrderService.getBaseMapper().selectOne(payOrderGw);
                if (ObjectUtil.isNotEmpty(payOrderEntity)) {
                    fansAwardEntityUpdate.setMchNo(payOrderEntity.getMchNo());
                }
                gtPayLogger.info(logPrefix + "此卡券核销更新数据，更新数据的信息是：{}", JSONUtil.toJsonStr(fansAwardEntityUpdate));
                fansAwardService.updateById(fansAwardEntityUpdate);

                //更新回调数据状态
                AwardCouponNotifyEntity couponNotifyUpdate = new AwardCouponNotifyEntity();
                couponNotifyUpdate.setCouponNotifyId(couponNotifyEntity.getCouponNotifyId());
                couponNotifyUpdate.setState(2);
                couponNotifyUpdate.setRemark("核销成功");
                gtPayLogger.info(logPrefix + "核销成功,更新的数据是：{}", JSONUtil.toJsonStr(couponNotifyUpdate));
                awardCouponNotifyService.updateById(couponNotifyUpdate);
            }
        } else {
            //卡券不是英雄啊平台创建
            AwardCouponNotifyEntity couponNotifyUpdate = new AwardCouponNotifyEntity();
            couponNotifyUpdate.setCouponNotifyId(couponNotifyEntity.getCouponNotifyId());
            couponNotifyUpdate.setState(2);
            couponNotifyUpdate.setRemark("此卡券不是营销平台创建");
            gtPayLogger.info(logPrefix + "处理逻辑,此卡券不是营销平台创建,更新的数据是：{}", JSONUtil.toJsonStr(couponNotifyUpdate));
            awardCouponNotifyService.updateById(couponNotifyUpdate);
        }
    }


    protected final String getBody(HttpServletRequest request) {
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8);
            StringBuffer bf = new StringBuffer();
            int len;
            char[] chs = new char[1024];
            while ((len = in.read(chs)) != -1) {
                bf.append(new String(chs, 0, len));
            }
            return bf.toString();
        } catch (Exception e) {
            log.error("请求头部取数据异常：{}", e.getMessage());
            throw new ServiceException(e.getMessage());
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (Exception e) {
                    log.error("流关闭异常:{}", e.getMessage());
                }
            }
        }
    }
}
